package com.example.express.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * 顺丰丰桥API客户端（精简版）
 */
public class SfExpressClient {
    private final String clientCode;
    private final String checkWord;
    private final boolean isProd;
    private final OkHttpClient httpClient;

    // 环境URL
    private static final String URL_SANDBOX = "https://sfapi-sbox.sf-express.com/std/service";
    private static final String URL_PROD = "https://sfapi.sf-express.com/std/service";

    public SfExpressClient(String clientCode, String checkWord, boolean isProd) {
        this.clientCode = clientCode;
        this.checkWord = checkWord;
        this.isProd = isProd;
        this.httpClient = new OkHttpClient();
    }

    /**
     * 调用顺丰API
     * @param serviceCode 接口代码（如 "EXP_RECE_CREATE_ORDER"）
     * @param msgData 业务数据JSON字符串
     */
    public String callSfApi(String serviceCode, String msgData) throws IOException {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String requestId = UUID.randomUUID().toString().replace("-", "");

        try {
            // 1. 生成签名 - 根据顺丰官方文档
            String plainText = msgData + timestamp + checkWord;
            // 需要进行URL编码处理
            String encodedText = URLEncoder.encode(plainText, "UTF-8");

            // 进行MD5加密
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(encodedText.getBytes("UTF-8"));
            byte[] md = md5.digest();

            // 转换为Base64字符串
            String msgDigest = Base64.encodeBase64String(md);

            // 2. 构建请求参数
            FormBody formBody = new FormBody.Builder()
                    .add("partnerID", clientCode)
                    .add("requestID", requestId)
                    .add("serviceCode", serviceCode)
                    .add("timestamp", timestamp)
                    .add("msgData", msgData)
                    .add("msgDigest", msgDigest)
                    .build();

            // 3. 发送请求
            String url = isProd ? URL_PROD : URL_SANDBOX;
            Request request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();

            try (Response response = httpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("HTTP Error: " + response.code());
                return response.body().string();
            }
        } catch (Exception e) {
            throw new IOException("签名生成失败", e);
        }
    }

    /**
     * 快速生成下单JSON
     */
    /**
     * 快速生成下单JSON
     */
    public static String buildOrderJson(String orderId, String senderPhone, String receiverPhone) {
        JSONObject order = new JSONObject();
        order.put("orderId", orderId);
        order.put("expressType", "1"); // 1=标准快递
        order.put("payMethod", 1);      // 1=寄方付
        order.put("isReturnRoutelabel", 1); // 根据文档要求，默认返回路由标签

        // 收件人/寄件人信息
        JSONArray contacts = new JSONArray();
        contacts.add(new JSONObject()
                .fluentPut("contactType", 2) // 2=到件方信息(收件人)
                .fluentPut("contact", "张三")
                .fluentPut("tel", receiverPhone)
                .fluentPut("country", "CN")
                .fluentPut("province", "广东省")
                .fluentPut("city", "深圳市")
                .fluentPut("county", "南山区")
                .fluentPut("address", "科技园南区"));
        contacts.add(new JSONObject()
                .fluentPut("contactType", 1) // 1=寄件方信息(寄件人)
                .fluentPut("contact", "李四")
                .fluentPut("tel", senderPhone)
                .fluentPut("country", "CN")
                .fluentPut("province", "北京市")
                .fluentPut("city", "北京市")
                .fluentPut("county", "朝阳区")
                .fluentPut("address", "朝阳区xxx街道xxx号"));
        order.put("contactInfoList", contacts);

        // 添加物品信息
        JSONArray cargoDetails = new JSONArray();
        cargoDetails.add(new JSONObject()
                .fluentPut("name", "测试商品")        // 货物名称
                .fluentPut("count", 1)               // 货物数量
                .fluentPut("unit", "个")             // 货物单位
                .fluentPut("weight", 0.5)            // 单位重量(kg)
                .fluentPut("amount", 100.0)          // 货物单价
                .fluentPut("currency", "CNY"));      // 币别
        order.put("cargoDetails", cargoDetails);

        return order.toJSONString();
    }

    public String queryExpressRoute(String waybillNo) throws IOException {
        // 构建查询JSON
        JSONObject queryData = new JSONObject();
        queryData.put("language", "zh-CN");
        queryData.put("trackingType", 1); // 1:根据运单号查询
        queryData.put("trackingNumber", waybillNo);
        queryData.put("methodType", "1"); // 1:查询轨迹

        String msgData = queryData.toJSONString();

        // 调用查询接口
        return callSfApi("EXP_RECE_SEARCH_ROUTES", msgData);
    }

}
